<template>
  <h2>composition-api(组合式api)</h2>

  <h4>计数器</h4>
  <button @click="minus">-</button>
  <span>count: {{ count }}</span>
  <button @click="add">+</button>
  <div>doubleCount: {{ doubleCount }}</div>

  <h4>todolist</h4>
  <input type="text" v-model="textValue" />
  <button @click="submit">发布</button>
  <ul>
    <li v-for="item in list" :key="item.id">
      {{ item.name }} - <button @click="remove(item.id)">删除</button>
    </li>
  </ul>

  <h4>pro列表</h4>
  <ul>
    <li v-for="item in proList" :key="item.proid">{{ item.proname }}</li>
  </ul>
</template>

<script>
import { ref, onMounted } from "vue";

import useCounter from "@/hooks/useCounter";

export default {
  // setup选项函数就是组合式api的入口函数
  // 这里面是不能使用this
  setup() {
    // 希望一个变量由响应式，需要使用ref方法来定义这个变量

    const [count, add, minus, doubleCount] = useCounter(200);

    // 功能2
    const textValue = ref("");
    const list = ref([
      {
        id: 1,
        name: "zhangsan",
      },
      {
        id: 2,
        name: "lisi",
      },
    ]);
    const submit = () => {
      list.value.push({
        id: new Date().getTime(),
        name: textValue.value,
      });
      textValue.value = "";
    };
    const remove = (id) => {
      list.value = list.value.filter((item) => item.id !== id);
    };

    // 功能3
    const proList = ref([]);
    onMounted(() => {
      fetch("http://121.89.205.189:3000/api/pro/list")
        .then((response) => response.json())
        .then((res) => {
          proList.value = res.data;
        });
    });

    // 只有在这里return的东西，才可以在template里面使用
    return {
      count,
      add,
      minus,
      doubleCount,
      textValue,
      list,
      submit,
      remove,
      proList,
    };
  },
};
</script>
